package top.kaoshanji.p2ch07a;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.util.List;

/**
 * 代码清单-p2ch07a-239页a：考虑内存剩余量的备份任务的示例
 * author kaoshanji
 * ^_^
 * create time 2025/1/20 19:41
 */
public class MemoryPoolMXBeanExample01 implements Runnable {

    private MemoryPoolMXBean poolBean;

    public MemoryPoolMXBeanExample01() {
        init();
    }

    private void init() {
        List<MemoryPoolMXBean> beans = ManagementFactory.getMemoryPoolMXBeans();
        for (MemoryPoolMXBean bean: beans) {
            if ("Tenured Gen".equals(bean.getName())) {
                poolBean = bean;
                break;
            }
        }

        poolBean.setUsageThreshold(10 * 1024 * 1024);
    }

    @Override
    public void run() {

        while (true) {
            if (poolBean.isUsageThresholdExceeded()) {
                System.out.println("内存不足，暂停备份任务。");
            } else {
                System.out.println("执行备份任务。");
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }
}
